package com.hmall.item.web;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hmall.common.dto.PageDTO;
import com.hmall.item.mapper.ItemMapper;
import com.hmall.item.pojo.Item;
import com.hmall.item.service.IItemService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/item")
public class ItemController {

    @Autowired
    private IItemService itemService;

    @Autowired
    private ItemMapper itemMapper;

    @GetMapping("/list")
    public PageDTO<Item> pageList(int page ,int size){
        Page<Item> p = new Page<>(page,size);
//        Page<Item> page1 = itemService.page(p);
        Page<Item> itemPage = itemMapper.selectPage(p, null);
        PageDTO<Item> pageDTO = new PageDTO();

        pageDTO.setList(itemPage.getRecords());
        pageDTO.setTotal(itemPage.getTotal());
        return pageDTO;
    }

    @GetMapping("/{id}")
    public Item getById(@PathVariable Long id){
        Item item = itemService.getById(id);
        return item;
    }

    //新增商品
    @PostMapping
    public void addCommodity(@RequestBody Item item){
        itemService.save(item);
    }

    //下架请求
    @PutMapping("/status/{id}/{status}")
    public void status(@PathVariable Long id,@PathVariable int status){
        //查询商品状态，进行修改
        Item item = itemService.getById(id);
        //判断商品状态
        if(item != null){
            //非空
            item.setStatus(status);
            itemService.updateById(item);
        }
    }

    //修改商品
    @PutMapping
    public void updateCommodity(@RequestBody Item item){
        itemService.updateById(item);
    }

    //删除商品
    @DeleteMapping("/{id}")
    public void deleteCommodity(@PathVariable Long id){
        itemService.removeById(id);
    }
}
